package com.yl.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.auth.entity.Role;
import com.yl.auth.entity.User;
import com.yl.auth.entity.Users;
import com.yl.auth.mapper.UserMapper;
import com.yl.auth.model.vo.UserVo;
import com.yl.auth.service.RoleService;
import com.yl.auth.service.UserService;
import com.yl.auth.service.UsersService;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ln
 * @since 2023-07-18
 */
@Api(tags = "运营端-用户管理")
@RestController
@RequestMapping("/admin/auth/user")
public class  UserController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UsersService usersService;


    @ApiOperation(value = "查询所有的用户管理")
    @GetMapping("/findAllUser/{page}/{limit}")
    public Result<IPage> findAllUser(@PathVariable Integer page,@PathVariable Integer limit){
        Page<User> page1 = new Page<>(page, limit);
        IPage<User> userList = userService.findAllUser(page1);
        return Result.ok(userList);
    }
    @ApiOperation(value = "查询所有的角色管理")
    @GetMapping("/findRole")
    public Result findRole(){
        List<Role> list = roleService.listrole();
        return Result.ok(list);
    }
    @ApiOperation(value = "添加用户信息")
    @PostMapping("/adduser")
    public Result adduser(@RequestParam(value ="jueseList") List<Integer> jueseList,@RequestBody User user){

        Users users=new Users();
        users.setUsername(user.getZhanghao());
        users.setPassword(user.getMima());
        users.setName(user.getName());
        users.setImgurl(user.getToxiang());
        users.setPhone(user.getPhone());
        String l="1";
        users.setType(l);
        usersService.save(users);
        user.setUsersId(users.getId());
        userService.save(user);
        Integer uid = userMapper.selectMaxId();
        for (Integer id : jueseList) {
            userService.saveuser(id,uid);
        }
         return Result.ok();
    }
    /*图片上传上传图片接口*/
    /*图片上传地址*/
    String fileSavePath = "D:/vscode/codeylhomes/public/upload/";
    /*格式化时间*/
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
    @PostMapping("/saveUpload")
    @ApiOperation(value = "图片上传toxiang字段")
    @CrossOrigin
    public Result uploadFile (@ApiParam(name = "file", value = "上传", required = true) @RequestPart("file") MultipartFile file, HttpServletRequest request){
        /*将时间转化成字符串*/
        Date date = new Date();
        String directory = simpleDateFormat.format(date);
        /*文件路径是否存在
         * 如果不存在,则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        /*获取图片的名字*/
        String imageName = file.getOriginalFilename();
        System.out.println("图片上传位置" + fileSavePath + directory);
        /*给文件创建一个新的名字*/
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        /*图片新的名字*/
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        System.out.println("上传的图片位置" + fileSavePath + directory + newFileName);
        /*创建新文件*/
        File newFile = new File(fileSavePath + directory + newFileName);
        try {
            file.transferTo(newFile);
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("图片上传成功的url:" + url);
            String sql = "/upload/" + directory + newFileName;
            /*返回给前端的字符串地址,然后添加的时候将这一串字符串加入到数据库中*/
            System.out.println(sql);
            return Result.ok(sql);
        } catch (IOException e) {
            return Result.ok();
        }
    }
    //删除---------------------------------------------------------
    @ApiOperation(value = "根据id删除用户及用户角色")
    @DeleteMapping("/removeDataById/{id}")
    public Result removeDataById(@PathVariable Integer id){
        User byId = userService.getById(id);
        usersService.removeById(byId.getId());
        userService.removeById(id);
        userService.removeRole(id);
        return Result.ok();
    }
    //修改--------------------------------------------------------
    @ApiOperation(value = "根据id查询用户信息-修改回显")
    @GetMapping("/getByIdUser/{id}")
    public Result getByIdUser(@PathVariable Integer id){
        User byId1 = userService.getById(id);
        return Result.ok(byId1);
    }
    @ApiOperation(value = "根据id查询中间表角色信息-修改回显")
    @GetMapping("/getByIdRole/{id}")
    public Result getByIdRole(@PathVariable Integer id){
        List<Integer> list=roleService.getByIdRole(id);
        System.out.println(list+"---------------------------");
        return Result.ok(list);
    }
    @ApiOperation(value = "根据id修改用户信息")
    @PostMapping("/update")
    public Result update(@RequestBody User user,@RequestParam(value ="jueseList") List<Integer> jueseList){
        Users users=new Users();
        users.setId(user.getUsersId());
        users.setName(user.getName());
        users.setPhone(user.getPhone());
        users.setUsername(user.getZhanghao());
        users.setPassword(user.getMima());
        users.setImgurl(user.getToxiang());
        String l="1";
        users.setType(l);
        usersService.updateById(users);
        userService.updateById(user);
        user.setUsersId(users.getId());
        userService.removeRole(user.getId());
        for (Integer id1 : jueseList) {
            userService.saveuser(id1,user.getId());
        }
       return Result.ok();
    }

//    @GetMapping("/ylogin")
//    @ApiOperation(value = "运营端登录功能")
//    public Result yunlogin(@ApiParam("用户名") UserVo userVo) {
//        if(userVo!=null) {
//            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(User::getUsername,userVo.getUsername());
//            wrapper.eq(User::getPassword,userVo.getPassword());
//            User one = userService.getOne(wrapper);
//            return Result.ok(one);
//        }else {
//            return Result.fail();
//        }
//    }
//    @GetMapping("/ylogins")
//    @ApiOperation(value = "运营端登录功能")
//    public Result yunlogins(@ApiParam("用户名") UserVo userVo) {
//        if(userVo!=null) {
//            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(User::getUsername,userVo.getUsername());
//            wrapper.eq(User::getPassword,userVo.getPassword());
//            User one = userService.getOne(wrapper);
//            return Result.ok(one);
//        }else {
//            return Result.fail();
//        }
//    }



}

